//
//  WBStatusViewModel.swift
//  SinaWeibo_Swift
//
//  Created by TianZhen on 16/4/14.
//  Copyright © 2016年 TianZhen. All rights reserved.
//

import UIKit

class WBStatusViewModel: NSObject {

    static let sharedInstance: WBStatusViewModel = WBStatusViewModel()
    
    /**     加载微博数据     */
    func loadStatus(loadStatusCallback: (statuses: [WBStatus]?, error: NSError?) -> ()) {
        // 判断accessToken是否为空
        guard let access_token = WBUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            // accessToken为空
            let error = WBNetToolError.emptyToken.error()
            loadStatusCallback(statuses: nil , error: error)
            return
        }
        
        // url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 参数
        let parameters = ["access_token": WBUserAccountViewModel.sharedInstance.userAccount!.access_token!]
        
        // 3.发送请求
        WBNetTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            
            // 获取微博数据
            if let dict = responseObject as? [String: AnyObject], let statusesDict = dict["statuses"] as? [[String: AnyObject]] {
                
                // 定义数组来保存转好的微博模型
                var statusModels: [WBStatus] = []
                
                // 遍历每个字典
                for dict in statusesDict {
                    // 字典转模型
                    let status = WBStatus(dict: dict)
                    
                    // 将模型添加到数组里面
                    statusModels.append(status)
                }
                loadStatusCallback(statuses: statusModels, error: nil)
            }
            
            }) { (task, error) -> Void in
                loadStatusCallback(statuses: nil, error: error)
        }
    }
}